#include "chatcontroller.h"
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>


ChatController::ChatController(QObject *parent) : QObject(parent)
{
    m_chatClient = new ChatClient(QUrl(QStringLiteral("ws://192.168.2.162:8070/ws")),true,this);
    connect(m_chatClient,&ChatClient::textMessageReceived,this,&ChatController::onTextMessageReceived);

    m_messageModel = new MessageModel(this);

    m_chatAudio = new ChatAudio(this);
    connect(m_chatAudio,&ChatAudio::inputStateChanged,this,&ChatController::onAudioInputStateChanged);
    connect(m_chatAudio,&ChatAudio::outputStateChanged,this,&ChatController::onAudioOutputStateChanged);
}

MessageModel *ChatController::messageModel(){
    return m_messageModel;
}

ChatAudio *ChatController::chatAudio(){
    return m_chatAudio;
}

void ChatController::onTextMessageReceived(QString message){
    QJsonParseError jsonpe;
    QJsonDocument json = QJsonDocument::fromJson(message.toLocal8Bit(), &jsonpe);
    if (jsonpe.error == QJsonParseError::NoError)
    {
        if (json.isObject()) {
            QJsonObject obj = json.object();
            int msgtype = obj["msg_type"].toInt();
            switch(msgtype){
            case ChatClient::UserListRole:break;
            case ChatClient::BroadcastRole:
            case ChatClient::AudioRole:
                QString message_str = obj["message"].toString();
                QString thismessage;
                if(msgtype == ChatClient::AudioRole){
                    thismessage = QByteArray::fromBase64(obj["message"].toString().toLatin1());
                }else{
                    thismessage = message_str;
                }

                QString time = obj["time"].toString();
                QJsonObject sender = obj["sender"].toObject();
                QString sendername = sender["username"].toString();
                int senderid = sender["id"].toInt();
                m_messageModel->append({thismessage,sendername,"",senderid,time,msgtype});
                break;
            }
        }
    }
}

void ChatController::inputMessageSend(QString message){

    QJsonObject object
    {
        {"message",message},
        {"msg_type",1}
    };
    QJsonDocument json(object);
    QByteArray json_str = json.toJson();
    m_chatClient->send(json_str);
}

void ChatController::onAudioInputStateChanged(QAudio::State audioState){
    switch(audioState){
    case QAudio::StoppedState:
    case QAudio::SuspendedState:
        QString data = m_chatAudio->getData().toBase64();
        QJsonObject object
        {
            {"message",data},
            {"msg_type",ChatClient::AudioRole}
        };
        QJsonDocument json(object);
        QByteArray json_str = json.toJson();
        m_chatClient->send(json_str);
        m_chatAudio->clearData();
        break;
    }
}

void ChatController::onAudioOutputStateChanged(QAudio::State audioState){
    
}
